# -*- encoding: utf-8 -*-
import logging
from offline_calc.handler import OfflineCalculationHandler
from common.const import IntervalType
from django.conf import settings
from common.timeutil import get_interval_end_pair
from common.cp.friday import marketing_cached_handler as handler

_LOGGER = logging.getLogger(__name__)


class Command(OfflineCalculationHandler):
    def __init__(self):
        super(Command, self).__init__()
        self.index_list = settings.CP_INDEX
        self.filtered_name_list = {
            handler.ExternalEnum.DailySummary: [IntervalType.DAY]
        }
        self.summary_name = handler.ExternalEnum.DailySummary

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)

    def handle(self, **kwargs):
        super(Command, self).handle(**kwargs)
        merchant = kwargs['merchant']
        target_event = kwargs['target_event']
        self.index_list = self.index_list if not merchant else [index for index in self.index_list if index == merchant]
        for index in self.index_list:
            for name, interval_type_list in self.filtered_name_list.items():
                for interval_type in interval_type_list:
                    if target_event and name.value != target_event:
                        continue
                    window_list = self.get_window_interval(interval_type.value)
                    for window in window_list:
                        start_time, end_time = get_interval_end_pair(interval_type, self.base_time, window)
                        time_range = [start_time, end_time]
                        print(index, name, interval_type.value, time_range)
                        try:
                            self.pool.apipe(self.start_execution, handler.create_aggregation_data, interval_type,
                                            name.value,
                                            self.base_time, index, window,
                                            dict(idx=index, handler_name=name, interval_type=interval_type,
                                                 time_range=time_range))
                        except Exception as e:
                            _LOGGER.exception('ES Create Report Error')
        self.pool.close()
        self.pool.join()
